package com.study.juc;

import java.util.concurrent.CountDownLatch;

/**
 * @author ysy
 * @version 1.0
 * @Title: CountDownLatchTest
 * @Note <b>ProjectName:</b> Pre-research
 * <br><b>PackageName:</b> com.study.juc
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>
 */
public class CountDownLatchTest {
    
    /**
     * 主要用途：用于阻塞一个线程，等待其它线程先后到达某个条件的时候，再执行这个线程的后续操作
     * 1. 构造器：CountDownLatch(int count);//参数count为计数值
     * 2. 核心API：
     *      void await();   // 调用await()方法的线程会被挂起，它会等待直到count值为0才继续执行
     *      boolean await( longtimeout, TimeUnit unit); // 和await()类似，只不过等待一定的时间后count值还没变为0的话就会继续执行
     *      void countDown(); //count值减一
     **/
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(2);
        new Thread() {
            public void run() {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
        }.start();

        new Thread() {
            public void run() {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
        }.start();
        try {
            System.out.println("等待2个子线程执行完毕...");
            latch.await();
            System.out.println("2个子线程已经执行完毕");
            System.out.println("继续执行主线程");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
